package
{
	
	import com.qs.calendar.Calendar;
	import com.qs.calendar.CalendarSet;
	import com.qs.calendar.iParser;
	import com.qs.controls.CalendarDisplay;
	import com.qs.utils.DateRange;
	import com.qs.utils.DateUtils;
	import com.qs.utils.DebugMessage;
	import com.qs.utils.DebugPanel;
	
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import mx.controls.Alert;
	import mx.controls.DateChooser;
	import mx.controls.TextInput;
	import mx.controls.ToggleButtonBar;
	import mx.core.Application;
	import mx.managers.PopUpManager;
	import mx.rpc.AsyncToken;
	import mx.rpc.Responder;
	import mx.rpc.http.mxml.HTTPService;
	import mx.utils.URLUtil;
	
	public class app_code extends Application
	{
		public function app_code()
		{
			super();
			
			calLoader = new HTTPService();
			calLoader.resultFormat = "text";
			
			/*  memberLoader.addEventListener(Event.COMPLETE, loadMember);
			xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
			alltimeLoader.addEventListener(Event.COMPLETE, loadAllTime); */
			/* 
			xmlLoader.load(new URLRequest("http://ec2-174-129-209-117.compute-1.amazonaws.com/endar_event/get_best_time_xml/"));
			memberLoader.load(new URLRequest("http://ec2-174-129-209-117.compute-1.amazonaws.com/endar_event/list_xml"));			
			alltimeLoader.load(new URLRequest("http://ec2-174-129-209-117.compute-1.amazonaws.com/endar_event/list_all_event_times_xml/"));
			 */
		}		
		
		protected static const displayOptions:Array = ['month','week','day']
		
		public var calLoader:HTTPService;
		public var calUrl:TextInput;
		[Bindable] public var displayMode:ToggleButtonBar;		
		[Bindable] public var cal:CalendarDisplay;
		public var chooser:DateChooser;
		
		public var busy:Busy;
		public var debugPanel:DebugPanel;
		
		
		
		[Bindable] public var calSet:CalendarSet = new CalendarSet();
		[Bindable] public var memberLoader:URLLoader = new URLLoader();
		[Bindable] public var xmlLoader:URLLoader = new URLLoader();
		[Bindable] public var alltimeLoader:URLLoader = new URLLoader();
		[Bindable] public var my_xml:XML = new XML();
		[Bindable] public var my_best:XML = new XML();
		[Bindable] public var alltime:XML = new XML();
		
		[Bindable]public var startDate:Date = new Date();
		[Bindable]public var endDate:Date  = new Date();
		
		public function debug(str:String):void {
	    	debugPanel.addMessage(new DebugMessage(str));
		}
		
		
		public function loadMember(e:Event):void{
			my_xml = new XML(e.target.data);
		}
		
		public function loadAllTime(e:Event):void{
			alltime = new XML(e.target.data);
			var recordList:XMLList = alltime.record; 
			
			for each (var recordElement:XML in recordList){
				//trace(recordElement);	
				
				var now:Date = new Date();
				var calData:String = 
				"BEGIN:VCALENDAR\r\n"+
				"PRODID:-//Google Inc//Google Calendar 70.9054//EN\r\n"+
				"VERSION:2.0\r\n"+
				"CALSCALE:GREGORIAN\r\n"+
				"METHOD:PUBLISH\r\n"+
				//"X-WR-CALNAME:test cal\r\n"+
				//"X-WR-TIMEZONE:America/Los_Angeles\r\n"+
				//"X-WR-CALDESC:\r\n"+
				"BEGIN:VEVENT\r\n"+
				"DTSTART;TZID=America/Los_Angeles:" + recordElement.dtstart +"\r\n"+
				"DTEND;TZID=America/Los_Angeles:" + recordElement.dtend +"\r\n"+
				//"DTSTART;TZID=America/Los_Angeles:20060923T160000\r\n"+
				//"DTEND;TZID=America/Los_Angeles:20060923T210000\r\n"+
				"DTSTAMP:"+DateUtils.toIcsDate(now) + "T" + DateUtils.toIcsTime(now)+"Z\r\n"+
				//"DTSTAMP:20060907T165551Z\r\n"+
				"ORGANIZER;CN=test cal:MAILTO:0vpmlit9621663ap27ilpg4hr0@group.calendar.goog\r\n"+
				" le.com\r\n"+
				"UID:j1o618k1tklj779nu2kgj9560s@google.com\r\n"+
				"CLASS:PRIVATE\r\n"+
				"CREATED:20060907T165444Z\r\n"+
				"LAST-MODIFIED:20060907T165444Z\r\n"+
				"LOCATION:\r\n"+
				"SEQUENCE:0\r\n"+
				"STATUS:CONFIRMED\r\n"+
				"DESCRIPTION:" + recordElement.description +  "\r\n"+
				"SUMMARY:"+recordElement.summary+"\r\n"+
				//"SUMMARY:timed event\r\n"+
				"TRANSP:OPAQUE\r\n"+
				"END:VEVENT\r\n"+
				/*"BEGIN:VTIMEZONE\r\n"+
				"TZID:America/Los_Angeles\r\n"+
				"X-LIC-LOCATION:America/Los_Angeles\r\n"+
				"BEGIN:STANDARD\r\n"+
				"TZOFFSETFROM:-0700\r\n"+
				"TZOFFSETTO:-0800\r\n"+
				"TZNAME:PST\r\n"+
				"DTSTART:19701025T020000\r\n"+
				"RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\r\n"+
				"END:STANDARD\r\n"+
				"BEGIN:DAYLIGHT\r\n"+
				"TZOFFSETFROM:-0800\r\n"+
				"TZOFFSETTO:-0700\r\n"+
				"TZNAME:PDT\r\n"+
				"DTSTART:19700405T020000\r\n"+
				"RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=1SU\r\n"+
				"END:DAYLIGHT\r\n"+
				"END:VTIMEZONE\r\n"+*/
				"END:VCALENDAR";
				
				var p:iParser = new iParser();
				var calendar:Calendar  = p.parse(calData)[0];
				calendar.contextColor = 0xBB00FF;
				calendar.name = "alltime";
				calSet.calendars = calSet.calendars.concat([calendar]);							
				cal.dataProvider = calSet.events;
				busy.currentState = "free";				
			}						
		}		
		
		public function LoadXML(e:Event):void{
			if (e.target.data == "error"){
				Alert.show("Load Best Time failed!", "Error!");				
				return;
			}					
				my_best = new XML(e.target.data);			
			
				var now:Date = new Date();
				startDate 	= new Date(""+my_best.dtstart);
				endDate		= new Date(""+my_best.dtend);
				
				//debug(startDate.toDateString());
				//debug(endDate.toDateString());
								 
				var calData:String = 
				"BEGIN:VCALENDAR\r\n"+
				"PRODID:-//Google Inc//Google Calendar 70.9054//EN\r\n"+
				"VERSION:2.0\r\n"+
				"CALSCALE:GREGORIAN\r\n"+
				"METHOD:PUBLISH\r\n"+
				//"X-WR-CALNAME:test cal\r\n"+
				//"X-WR-TIMEZONE:America/Los_Angeles\r\n"+
				//"X-WR-CALDESC:\r\n"+
				"BEGIN:VEVENT\r\n"+
				"DTSTART;TZID=America/Los_Angeles:" + my_best.dtstart1 +"\r\n"+
				"DTEND;TZID=America/Los_Angeles:" + my_best.dtend1 +"\r\n"+
				//"DTSTART;TZID=America/Los_Angeles:20060923T160000\r\n"+
				//"DTEND;TZID=America/Los_Angeles:20060923T210000\r\n"+
				"DTSTAMP:"+DateUtils.toIcsDate(now) + "T" + DateUtils.toIcsTime(now)+"Z\r\n"+
				//"DTSTAMP:20060907T165551Z\r\n"+
				"ORGANIZER;CN=test cal:MAILTO:0vpmlit9621663ap27ilpg4hr0@group.calendar.goog\r\n"+
				" le.com\r\n"+
				"UID:j1o618k1tklj779nu2kgj9560s@google.com\r\n"+
				"CLASS:PRIVATE\r\n"+
				"CREATED:20060907T165444Z\r\n"+
				"LAST-MODIFIED:20060907T165444Z\r\n"+
				"LOCATION:\r\n"+
				"SEQUENCE:0\r\n"+
				"STATUS:CONFIRMED\r\n"+
				"DESCRIPTION:"+my_best.description+"\r\n"+
				"SUMMARY:"+my_best.summary+"\r\n"+
				//"SUMMARY:timed event\r\n"+
				"TRANSP:OPAQUE\r\n"+
				"END:VEVENT\r\n"+
				/*"BEGIN:VTIMEZONE\r\n"+
				"TZID:America/Los_Angeles\r\n"+
				"X-LIC-LOCATION:America/Los_Angeles\r\n"+
				"BEGIN:STANDARD\r\n"+
				"TZOFFSETFROM:-0700\r\n"+
				"TZOFFSETTO:-0800\r\n"+
				"TZNAME:PST\r\n"+
				"DTSTART:19701025T020000\r\n"+
				"RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\r\n"+
				"END:STANDARD\r\n"+
				"BEGIN:DAYLIGHT\r\n"+
				"TZOFFSETFROM:-0800\r\n"+
				"TZOFFSETTO:-0700\r\n"+
				"TZNAME:PDT\r\n"+
				"DTSTART:19700405T020000\r\n"+
				"RRULE:FREQ=YEARLY;BYMONTH=4;BYDAY=1SU\r\n"+
				"END:DAYLIGHT\r\n"+
				"END:VTIMEZONE\r\n"+*/
				"END:VCALENDAR";
				
				var p:iParser = new iParser();
				var calendar:Calendar  = p.parse(calData)[0];
				calendar.contextColor = 0xBB0000;
				calendar.name = "besttime";
				calSet.calendars = calSet.calendars.concat([calendar]);							
				cal.dataProvider = calSet.events;
				busy.currentState = "free"; 		
				
				load();	
		}		
			
		protected function addCalendar():void
		{
			var createDlg:CreateCalendarDialog = new CreateCalendarDialog();
			createDlg.loadCallback = function(dlg:CreateCalendarDialog):void
			{
				loadCalendar(dlg.url,dlg.calendarName,dlg.color);
			}
			
			PopUpManager.addPopUp(createDlg,this,true);
			PopUpManager.centerPopUp(createDlg);
		}
		protected function showHelp():void
		{
			var hlp:Help = new Help();
			PopUpManager.addPopUp(hlp,this,true);
			PopUpManager.centerPopUp(hlp);
		}
		
		protected function init():void{
			memberLoader.addEventListener(Event.COMPLETE, loadMember);
			xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
			alltimeLoader.addEventListener(Event.COMPLETE, loadAllTime);
			
			xmlLoader.load(new URLRequest("http://ec2-174-129-209-117.compute-1.amazonaws.com/endar_event/get_best_time_xml/"));
			memberLoader.load(new URLRequest("http://ec2-174-129-209-117.compute-1.amazonaws.com/endar_event/list_xml"));			
			alltimeLoader.load(new URLRequest("http://ec2-174-129-209-117.compute-1.amazonaws.com/endar_event/list_all_event_times_xml/"));	
			
		}
		
		protected function load():void
		{	
			//showHelp();									
			//goToToday();			
			//debug(startDate.toDateString());
			//debug(endDate.toDateString());						
			cal.range = new DateRange(startDate, endDate);			
			
		}

		private function loadCalendar(url:String, name:String, color:uint):void
		{			
			busy.currentState = "busy";
			url = URLUtil.getFullURL(systemManager.loaderInfo.url,url);
			calLoader.url = url;
			var token:AsyncToken = calLoader.send();
			token.addResponder(new Responder(
				function(param:*):void {
					var calData:String = (token.result as String);
					var p:iParser = new iParser();
					var calendar:Calendar  = p.parse(calData)[0];
					calendar.contextColor = color;
					calendar.name = name;
					calSet.calendars = calSet.calendars.concat([calendar]);							
					cal.dataProvider = calSet.events;
					busy.currentState = "free";
				},
				function (param:*):void {
				
					Alert.show("calendar load failed");
					busy.currentState = "free";
				}));				
				
		}
		
		protected function goToToday():void
		{
			cal.range = new DateRange(new Date(),new Date());
		}
		protected function formatDate(d:Date):String
		{
			var r:String = d.toDateString();
			return r;
		}
		public function removeCalendar(cal:Object):void
		{
			var cals:Array = calSet.calendars.concat();
			for(var i:int = 0;i<cals.length;i++)
			{
				if(cals[i] == cal)
				{
					cals.splice(i,1);
					calSet.calendars = cals;
					return;
				}
			}
		}
		
		protected function updateRange():void
		{
			cal.displayMode = "auto";l
			if(chooser.selectedRanges.length == 0)
				return;
			var selRange:Object = chooser.selectedRanges[0];
			cal.range = new DateRange(selRange.rangeStart,selRange.rangeEnd);			
		}
		
		protected function rangeChangeHandler():void
		{
			chooser.selectedRanges = [ {rangeStart: cal.range.start, rangeEnd: cal.range.end} ];
			chooser.displayedYear = cal.range.start.fullYear;
			chooser.displayedMonth = cal.range.start.month;
		}
		
		protected function displayModeHandler():void
		{
			switch(cal.displayMode)
			{
				case "day":
				case "days":
					displayMode.selectedIndex = 2;
					break;
				case "week":
				case "weeks":
					displayMode.selectedIndex = 1;
					break;
				case "month":
				default:
					displayMode.selectedIndex = 0;
					break;					
			}
		}
		
		protected function headerClickHandler(d:Date):void
		{
			cal.displayMode = "auto";
			cal.range = new DateRange(d,d);						
		}

		protected function dayClickHandler(d:Date):void
		{
			cal.displayMode = "auto";
			cal.range = new DateRange(d,d);						
		}
		
		protected function displayModeItemClickHandler():void
		{
			cal.displayMode=displayOptions[displayMode.selectedIndex];
		}
		
		protected var _colors:Array = [
			0xBB0000,
			0x00BB00,
			0x0000BB,
			0xBBBB00,
			0xBB00BB,
			0x00BBBB
		];
		
		
	}
}
